<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/


jimport( 'joomla.application.component.model' );
JTable::addIncludePath(JPATH_COMPONENT_SITE.DS.'tables'); 

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JobBoardModelJAJobAlerts extends JModel
{
    var $_pagination = null;
    var $_table = null;
    var $_emp_pagination = null;
	
    function __construct($jbconfig = array()){
        parent::__construct($jbconfig);
        
        $this->set('name', 'jobalerts');
        $this->set('fullname', JBPREFIX.'jobalerts');
    }
    
    
//  PhuongLH - Save jobs - End -
     
    function remove($task = 'remove'){
        $cid = JRequest::getVar('cid',array(), 'post', 'array');
        $n =  count($cid);
        JArrayHelper::toInteger( $cid );
        $user = &JFactory::getUser();
		
        if($n && $user->id){
            if($task == 'remove'){
                $query = "DELETE FROM #__ja_jobalerts WHERE user_id = ". (int)$user->id ." AND item_id = ". implode(" OR item_id = ", $cid);
                echo $query;
                $db = &JFactory::getDBO();
                $db->setQuery($query);
                if($db->query()){
                    return $n; 
                }
            }
        }
        
        return 0;
    }

	function _buildQuery($limitstart, $limit, $dosearch=false){
    	global $mainframe, $option;		
		$db = JFactory::getDBO();
    	$user = JFactory::getUser();
    	// Get the WHERE and ORDER BY clauses for the query
		$orderby	= $this->_buildContentOrderBy();		
		
		$query = "SELECT s.* "
        		 ."FROM #__ja_jobalerts as s"
        		 ." WHERE s.user_id=".(int)$user->id
        		 . $orderby;
		
        return $query;
    }
    
    
	function _buildContentOrderBy()
	{
		global $mainframe, $option;
		
		$option_1 = $option.'.jajobalerts';
//		$filter_order		= JRequest::getVar('filter_order', 's.posted_date');
		$filter_order	= "s.".$mainframe->getUserStateFromRequest( $option_1.'.filter_order',	'filter_order',	'posted_date','word' );
		if ($filter_order=="s.location_name")
			$filter_order = "location_name";
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option_1.'.filter_order_Dir',	'filter_order_Dir',	'','word' );
		
		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.' , s.id ';
		
		return $orderby;
	}    
    
    
	function getItems($search=false){
		global $mainframe, $option;
		$db = JFactory::getDBO();
		
	    $limit		= $mainframe->getUserStateFromRequest( $option.'.jajobalerts.limitstart', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( $option.'.jajobalerts.limitstart', 'limitstart', 0, 'int' );
		
		if(!$limit) $limit = $this->getTotal();
		$db = &JFactory::getDBO();
		
		$query = $this->_buildQuery($limitstart, $limit, $search);
		
		$db->setQuery($query);
		$items = $db->loadObjectList();		
		for ($i=0;$i<count($items);$i++)
		{
			$items[$i]->title = JFilterInput::_decode($items[$i]->title);
			$items[$i]->title = JFilterInput::clean($items[$i]->title);
			if ($items[$i]->category!='')
			{
				$query = "SELECT name FROM #__ja_categories WHERE id IN (".$items[$i]->category.")";	
				$db->setQuery($query);			
				$result = $db->loadResultArray();
				if (count($result)>0)
					$result = implode(', ',$result);
				$items[$i]->category = $result;
			}
			else 
				$items[$i]->category = JText::_("All");
			if ($items[$i]->location==''||$items[$i]->location==null)
				$items[$i]->location = JText::_("All");
			else 
			{
				$query = "SELECT name FROM #__ja_location WHERE id IN (".$items[$i]->location.")";	
				$db->setQuery($query);			
				$result = $db->loadResultArray();
				if (count($result)>0)
					$result = implode(', ',$result);
				$items[$i]->location = $result;
			}
		}
		return $items;
	}    
    
    
    /**
    * Get jobalert table instance
    * @return JobBoardTableJA_JobAlert Instance of jobalert table
    */
    function getTable(){
       if($this->_table == null){
           $this->_table = &JTable::getInstance('ja_jobalerts', 'JobBoardTable');
       }
       return $this->_table;
    }
    
	/**
	* Get configuration item
	* @return Config Table object
	*/
	function getItem(){
		static $item;
		if (isset($item)) {
			return $item;
		}

		$table = $this->getTable();

		// Load the current item if it has been defined
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($cid, array(0));
		if ($cid[0]!=0) {
			$table->load($cid[0]);
		}

	    $item = $table;
	    return $item;	    
	}    
    
	/** 
	* Store configuration item
	* @param array The post array
	*/
	function store(){
	    // Initialize variables
		$db		=& JFactory::getDBO();
		$row	=& $this->getItem();
		
		$post	= $this->getState( 'request' );
		
		if (!$row->bind( $post )) {
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		if (isset($post['category']))
		{
			for ($i=0;$i<count($row->category);$i++)
				if (($row->category[$i]==0)||($row->category[$i]==""))
					unset($row->category[$i]);
			if ($row->category)
				$row->category = implode(',',$row->category);
		}
		else 
		{
			$row->category = '';
		}
		if (isset($post['location']))
		{
			for ($i=0;$i<count($row->location);$i++)
				if (($row->location[$i]==0)||($row->location[$i]==""))
					unset($row->location[$i]);
			if ($row->location)
				$row->location = implode(',',$row->location);
		}
		else 
		{
			$row->location = '';
		}
//		for ($i=0;$i<count($row->job_distance);$i++)
//			if (($row->job_distance[$i]==0)||($row->job_distance[$i]==""))
//				unset($row->job_distance[$i]);
		
//		$row->job_distance = implode(',',$row->job_distance);
		if (!$row->sendmail_duration)
			$row->job_ids = '';
		
		if (!$row->check())
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		if (!$row->store())
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		else 
			if ($row->sendmail_duration)
				findJobForJobAlert($row);
		return $row->id;
	}	
	
	function delete()
	{
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($cid, array(0));
		if ($cid[0]!=0) {
			$db = JFactory::getDBO();
			$query = "DELETE FROM #__ja_jobalerts WHERE id=".(int)$cid[0];
			$db->setQuery($query);
			$db->query();
			return true;	
		}
		return false;
	}
	
    /**
    * Get page navigator object
    * @return 
    */
    /*	
    function &getPagination(){
        if ($this->_pagination == null) {
            $this->getItems();
        }
        return $this->_pagination;
    }*/
    
    /*function getItems(){
        global $mainframe;
        
        $user = &JFactory::getUser();
        
        if($user->id){
            $limit                = $mainframe->getUserStateFromRequest( 'global.list.limit',                            'limit',            $mainframe->getCfg( 'list_limit' ),    'int' );
            $limitstart            = $mainframe->getUserStateFromRequest( JBCOMNAME.'.jobalert.limitstart',        'limitstart',        0,                'int' );
            
            $db = &JFactory::getDBO();

            $db->setQuery($this->_buildListQuery());
            
            $items = $db->loadObjectList();
            
            $total = count( $items );

            jimport('joomla.html.pagination');
            $this->_pagination = new JPagination( $total, $limitstart, $limit );
            
            // slice out elements based on limits
            $list = array_slice( is_array($items) ? $items : array(), $this->_pagination->limitstart, $this->_pagination->limit );
            
            return $list;
        }
        
        return array();        
    }*/
    
    function getEmPagination()
    {
    	return $this->_emp_pagination;
    }
    
	function getUserList() {
		global $jbconfig;
		$db = JFactory::getDBO ();
		$search = JRequest::getVar ( 'user_search' );
		$where = '';
		$limitstart = JRequest::getVar('limitstart',0);
		JRequest::setVar('limitstart',$limitstart);
		require_once (JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'jaemployers.php');
		$em_model = new JAJobBoardModelJAEmployers ( );
		$employer_list = $em_model->getItems ();
		$this->_emp_pagination = $em_model->getPagination();
		$user_list = array ();
		if ($search) {
			$where .= " and (";
			$where .= " (name LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
			$where .= " or (username LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
			$where .= " or (email LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
			$where .= ")";
		}
		$temp_user_id = array ();
		for($i = 0; $i < count ( $employer_list ); $i ++) {
			if ($employer_list [$i]->id)
				$temp_user_id [] = $employer_list [$i];
		}
		
		return $temp_user_id;
	}
    

}
?>
